package com.zixue.heima.progressNetty;

import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;

/**
 * @ClassName : nianbaoClientShotConnect
 * @Description : TODO
 * @Author : chunxiong
 * @Date : 2025/5/12 15:44
 * @Version 1.0
 */
public class nianbaoClientShotConnect {
    public static void main(String[] args) throws InterruptedException {
        for (int i = 0; i < 10; i++) {
            extracted();
        }
    }

    private static void extracted() {
        NioEventLoopGroup worker = new NioEventLoopGroup();
        try {
            new Bootstrap()
                    .group(worker)
                    .channel(NioSocketChannel.class)
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            ch.pipeline().addLast(new ChannelInboundHandlerAdapter(){
                                //连上服务器就会触发 Active事件
                                @Override
                                public void channelActive(ChannelHandlerContext ctx) throws Exception {
                                    super.channelActive(ctx);
                                    ByteBuf buffer = ctx.alloc().buffer(16);
                                    //加16看看 会不会产生半包
                                    buffer.writeBytes(new byte[]{0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16});
                                    ctx.writeAndFlush(buffer);

                                    //解决粘包问题， 1。短连接连接建立1次就断开，
                                    ctx.channel().close();
                                }
                            });
                        }
                    }).connect("localhost",8080)
                    .channel()
                    .closeFuture()
                    .sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally {
            worker.shutdownGracefully();
        }
    }
}
